﻿namespace KinonekoSoftware.CodariaDB.Documents.Index
{
    public class RegionEngine : _Delta<RegionCache>
    {

        //
        //    @ _Cache
        //    用于实现SpeciesCache的缓存，这有助于提高速度、降低内存占用
        //    并且更方便的实现，可观测对象的内存一致性
        private readonly Dictionary<string, int> _Cache      = new Dictionary<string, int>();
        private readonly List<RegionCache>       _collection = new List<RegionCache>();

        //-------------------------------------------------------------
        //
        //          Override Methods
        //
        //-------------------------------------------------------------

        public override string GetCollectionName() => CollectionNames.Cache_InstanceDB;


        protected internal override void OnDatabaseClosingInternal(ILogger logger)
        {
            base.OnDatabaseClosingInternal(logger);

            _Cache.Clear();
        }


        //-------------------------------------------------------------
        //
        //          Public Methods
        //
        //-------------------------------------------------------------

        public void AddCache(RegionCache cache)
        {
            if (cache is null)
            {
                return;
            }

            if (_Cache.TryGetValue(cache.Id, out var index))
            {
                ((IGlossaryOperation)cache).Update(this);
                InsideDB.Update(cache);
            }
            else
            {
                ((IGlossaryOperation)cache).Add(this);
                index = _collection.Count;
                _Cache.TryAdd(cache.Id, index);
                _collection.Add(cache);
                InsideDB.Insert(cache);
            }

            Modified(cache);

        }

        public void UpdateCache(RegionCache cache)
        {
            if (cache is null)
            {
                return;
            }

            // cache.TimeOfModified = DateTime.Now;
            InsideDB.Update(cache);

            ((IGlossaryOperation)cache).Update(this);
            Modified();
        }

        public void RemoveCache(RegionCache cache, bool softDelete = true)
        {
            if (cache is null)
            {
                return;
            }

            if (softDelete)
            {
                cache.IsDeleted = true;
                InsideDB.Update(cache);

            }
            else
            {
                InsideDB.Delete(cache.Id);

            }
            var id = cache.Id;

            if (_Cache.Remove(id, out var index))
            {
                _collection.RemoveAt(index);
            }

            ((IGlossaryOperation)cache).Remove(this);

            Queue.OnNext(new RemoveOP_InstanceCacheMSG
            {
                Id = cache.Id,
            });
            Modified();
        }

        public bool Has(string id) => InsideDB.HasID(id);


        #region Get

        /// <summary>
        /// 缓存命中的Get策略
        /// </summary>
        /// <param name="id">设定的ID</param>
        /// <returns></returns>
        public RegionCache Get(string id)
        {
            if (_Cache.TryGetValue(id, out var index) && index < _collection.Count)
            {

                return _collection[index];
            }

            return InsideDB.FindById(id);
        }


        /// <summary>
        /// 带缓存策略的Get
        /// </summary>
        /// <returns></returns>
        public IEnumerable<RegionCache> Get() => _collection;

        #endregion


        public override string EngineID => EngineNames.Cache_Region;
    }
}